﻿#--coding:utf-8--
from django.http import HttpResponse, HttpResponseRedirect,Http404
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.views.generic import list_detail
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
import forms
from models import *
from django.contrib.auth import *
from django.contrib.syndication import feeds
from dolist.registration.models import RegistrationProfile
from django.core import serializers
from JsonResponse import *

LOGIN_URL="/login/"


def authfeed(request,key,url, feed_dict=None):
    if not key:
        raise Http404, "No key."
    if not feed_dict:
        raise Http404, "No feeds are registered."
    try:
        user=RegistrationProfile.objects.get(activation_key=key)
        user=user.user
    except Exception :
        raise Http404,"Private key error."
 
    try:
        slug, param = url.split('/', 1)
    except ValueError:
        slug, param = url, ''

    try:
        f = feed_dict[slug]
    except KeyError:
        raise Http404, "Slug %r isn't registered." % slug

    try:
        feedgen = f(slug, request.path,user).get_feed(param)
    except feeds.FeedDoesNotExist:
        raise Http404, "Invalid feed parameters. Slug %r is valid, but other parameters, or lack thereof, are not." % slug

    response = HttpResponse(mimetype=feedgen.mime_type)
    feedgen.write(response, 'utf-8')
    return response

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

@login_required
def add_tip(request):
    """
    Allows a user to add a tip to the database.

    Context::
        form
            The form to add the tip.

    Template::
        tip/tip_add.html

    """
  
    if request.method == 'POST':
        form = forms.EditTipForm(request.POST)
        if form.is_valid():
            new_tip = Tip(        content=form.clean_data['content'],
                                  tag_list=form.clean_data['tag_list'],
                                  dostatus=form.clean_data['dostatus'],
                                  due_time=form.clean_data['due_time'],
                                  author=request.user)
            new_tip.save()
            return HttpResponseRedirect("/mytips/")
    else:
        form = forms.EditTipForm(initial={"due_time":datetime.datetime.now(),"dostatus":0})
   
    return render_to_response('tip/tip_add.html',
                              { 'form': form,'debug':True },
                              context_instance=RequestContext(request))


@login_required
def edit_tip(request, tip_id):
    """
    Allows a user to edit an existing tip.

    Context::
        form
            The form to add the tip.

        original
            The Snippet being edited.

    Template::
        tip/tip_add.html

    """
    tip = get_object_or_404(Tip,
                                pk=tip_id,
                                author__pk=request.user.id)
    if request.method == 'POST':
        form = forms.EditTipForm(request.POST)
        if form.is_valid():
            for field in ['content', 'tag_list', 'dostatus', 'due_time']:
                setattr(tip, field, form.clean_data[field])
            tip.save()
            return HttpResponseRedirect("/mytips/")
      
    else:
        form = forms.EditTipForm(initial=tip.__dict__)
    return render_to_response('tip/tip_add.html',
                              { 'form': form,
                                'original': tip },
                              context_instance=RequestContext(request))

@login_required
def del_tip(request, tip_id):
    """
    Allows a user to del an existing tip.

    Context::
        form
            The form to add the tip.

        original
            The Snippet being edited.

    Template::
        tip/tip_add.html

    """
    tip = get_object_or_404(Tip,
                                pk=tip_id,
                                author__pk=request.user.id)
                                
    tip.delete()

    return HttpResponseRedirect("/mytips/")

def tips_by_tag(request, slug):
    """
    List of Snippets with a particular Tag.

    Context::
    Same as the generic ``list_detail.object_list`` view, with
    one extra variable:

        object
            The Tag

    Template::
        cab/tag_detail.html

    """
    slug=unicode(slug,'utf-8')
    tag = get_object_or_404(Tag, slug__exact=slug)
    return list_detail.object_list(request,
                                   queryset=Tip.objects.get_by_tag(slug),
                                   extra_context={ 'object': tag },
                                   template_name='tip/tip_list.html'
                                   )
@login_required
def mytips_tag(request,slug):
    if request.has_key('type'):
       request.session['type']=request.GET['type']

    slug=unicode(slug,'utf-8')
    tag = get_object_or_404(Tag, slug__exact=slug)
    return list_detail.object_list(request,
                                   queryset=Tip.objects.filter(author__username__exact=request.user.username,tags__slug__exact=slug),
                                   extra_context={ 'object': tag },
                                   template_name='tip/tip_list.html'
                                   )


@login_required
def mytips(request):
##   return HttpResponse(request.user.username);
   if request.has_key('type'):
       request.session['type']=request.GET['type']
   return  list_detail.object_list(request,allow_empty=True,
              queryset=Tip.objects.get_by_author(request.user.username),
              extra_context={'debug':True},
              template_name='tip/tip_list.html')
              
@login_required
def mytips_todo(request):
##   return HttpResponse(request.user.username);
   if request.has_key('type'):
       request.session['type']=request.GET['type']

   return  list_detail.object_list(request,allow_empty=True,
              queryset=Tip.objects.filter(author__username__exact=request.user.username,dostatus=1) ,
              extra_context={'debug':True},
              template_name='tip/tip_list.html')

@login_required
def mytips_done(request):
##   return HttpResponse(request.user.username);
   if request.has_key('type'):
       request.session['type']=request.GET['type']

   return  list_detail.object_list(request,allow_empty=True,
              queryset=Tip.objects.filter(author__username__exact=request.user.username,dostatus=2) ,
              extra_context={'debug':True},
              template_name='tip/tip_list.html')


def notes_index(request,name):
    user=User.objects.get_or_create(username=name)[0]
    
    if user.is_active:
        if request.has_key('type'):
            request.session['type']=request.GET['type']
        return  list_detail.object_list(request,allow_empty=True,
                    queryset=Tip.objects.get_by_author(name),
                    extra_context={'debug':True,'cuser':user},
                    template_name='notes/index.html')

    else:
        return HttpResponse(u'Your are new user.')

def ajaxhello(request,tip_id):
    #obj=get_object_or_404(Tip, pk=tip_id)
    import ajaxProtocol
    
    #return JsonResponse(Tip.objects.filter(id=2))
    return ajaxProtocol.json_response(Tip.objects.filter(id=2))
    

def test(request):
    pass
##   import django
##   return django.views.generic_view()
   
##    return HttpResponse(u'ERR! 不存在  ！<br /> <a href="/gd/admin_editGDZ/">back!</a>')

